package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.FreezeDetail;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private FastFileStorageClient client;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;
    @DubboReference
    private CommentApi commentApi;


    //videoThumbnail:封面
    //videoFile:视频
    //发布视频
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile)
            throws IOException {
        //1、视频上传到FastDFS    abcasdsa.avi
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath path = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), filename, null);//文件inputsream，文件大小，文件后缀名，元数据
        String videoUrl = webServer.getWebServerUrl() + path.getFullPath();
        //2、封面图上传到阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(),
                videoThumbnail.getInputStream());
        //3、构造数据，存入到数据库中
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        mqMessageService.sendLogService(UserHolder.getUserId(), "0301", "video", videoId);

    }

    public static void main(String[] args) {
        String filename = "abcasdsa.avi";
        String name = filename.substring(filename.lastIndexOf("."));
        System.out.println(name);
    }

    //查询视频列表
    @Cacheable(key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+ '_' + #page+ '_' + #pagesize"
            , value = "video")  //video::userid_1_10   -- 10
    public PageResult queryVideoList(int page, int pagesize) {
        //1、查询redis中的推荐视频数据
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        //2、判断redis中的数据
        List<Video> list = new ArrayList<>();
        if (StringUtils.isEmpty(value)) {
            //2.1、如果Redis中的推荐数据不存在，查询MongoDB数据库
            list = this.findByMongoDB(page, pagesize);
        } else {
            //2.2、如果Redis中的推荐数据存在，根据redis中的value进行分页处理
            list = this.findByRedis(value, page, pagesize);
        }
        //3、查询数据获取List<Video>数据集合，构造List<VideoVo>数据
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //循环构造
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                String redisKey = Constants.MOVEMENTS_INTERACT_KEY + video.getId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                Boolean hasKey = redisTemplate.opsForHash().hasKey(redisKey, hashKey);
                if (hasKey) {
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        //4、封装返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    public List<Video> findByMongoDB(int page, int pagesize) {
        return videoApi.findAll(page, pagesize);
    }

    public List<Video> findByRedis(String value, int page, int pagesize) {
        String[] values = value.split(",");
        //判断，是否存在当前页的数据 1,2
        if ((page - 1) * pagesize < values.length) {
            List<Long> vids = Arrays.stream(values)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize)
                    .map(e -> Long.valueOf(e))  //对数组中每个元素进行处理
                    .collect(Collectors.toList()); //获取list集合
            return videoApi.findByVids(vids);
        } else {
            //公式  20 / 10 = 2   查询第4页   ： 2
            int redisPage = PageUtil.totalPage(values.length, pagesize);
            //page - 20 / 10
            return videoApi.findAll(page - redisPage, pagesize); //如果redis推荐数据不足，查询mongodb
        }
    }

    //视频点赞
    public Integer like(String videoId) {
        Boolean hasComment = commentApi.hasComment(videoId, UserHolder.getUserId(),
                4);
        if (hasComment) {
            //已点赞
            throw new BusinessException(ErrorResult.likeError());
        }
        //2、调用API保存互动数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(4);//点赞
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.savevideo(comment);
        //3、在redis中记录点赞状态  redis的数据类型：hash
        // redis的key   hashkey，hashvalue
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(redisKey, hashKey, "4");
        return count;
    }

    public Integer dislike(String videoId) {
        //1、判断是否已点赞，
        Boolean hasComment = commentApi.hasComment(videoId, UserHolder.getUserId(),
                4);
        if (!hasComment) {
            //未点赞，抛出异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //2、调用API删除互动数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(4);//点赞
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.deleteVideo(comment); //删除互动数据
        //3、删除Redis中记录的点赞状态
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(redisKey, hashKey);
        return count;
    }

    //查询视频评论列表
    public PageResult findAllComment(Integer page, Integer pagesize, String videoId) {
        List<Comment> comments = commentApi.findComments(videoId, 5, page, pagesize);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //2、获取评论发布人的id，获取用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //3、一个Comment转化一个CommentVo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                String redisKey = Constants.MOVEMENTS_INTERACT_KEY + "_" + comment.getId();
                String hashkey =  Constants.MOVEMENT_LIKE_HASHKEY +"_"+ UserHolder.getUserId().toString();
                Boolean hasKey = redisTemplate.opsForHash().hasKey(redisKey, hashkey);
                if(hasKey){
                    vo.setHasLiked(1);
                }else {
                    vo.setHasLiked(0);
                }
                vos.add(vo);
            }
        }
        //4、返回值
        return new PageResult(page, pagesize, 0l, vos);
    }
        //发布视频评论
    public void saveComments(String videoId, String comment) {
        //1、获取当前用户的ID
        Long userId = UserHolder.getUserId();
        String redisKey = Constants.USER_FREEZE + "_" + userId.toString();
        Boolean hasKey = redisTemplate.hasKey(redisKey);
        if (hasKey) {
            String toString = redisTemplate.opsForValue().get(redisKey);

            FreezeDetail freeze = JSON.parseObject(toString, FreezeDetail.class);
            Integer freezingRange = freeze.getFreezingRange();
            if (freezingRange == 2) {
                throw new BusinessException(ErrorResult.dongJieFaYan());

            }
        }

        //2、构造Comment对象
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(videoId));
        comment1.setCommentType(5);//评论
        comment1.setContent(comment);
        comment1.setUserId(userId);
        //3、调用API保存数据(保存数据之后，返回评论数量)
        Integer count = commentApi.savevideo(comment1);
        System.out.println("count = " + count);
    }

    //视频评论点赞
    public Integer commentsLike(String commentId) {
        Long userId = UserHolder.getUserId();
        Integer likeCount = commentApi.findById(commentId,userId);
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + "_" + commentId;
        String hashkey =  Constants.MOVEMENT_LIKE_HASHKEY +"_"+ UserHolder.getUserId().toString();
        redisTemplate.opsForHash().put(redisKey, hashkey, "1");
        return likeCount;
    }
    //视频评论取消点赞
    public Integer commentsDislike(String commentId) {
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + "_" + commentId;
        String hashkey =  Constants.MOVEMENT_LIKE_HASHKEY +"_"+ UserHolder.getUserId().toString();
        Boolean hasKey = redisTemplate.opsForHash().hasKey(redisKey, hashkey);
        if(!hasKey){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Integer likeCount = commentApi.uodate(commentId);
        redisTemplate.opsForHash().delete(redisKey,hashkey);
        return likeCount;
    }

//    //查询视频列表
//    public PageResult queryVideoList(int page, int pagesize) {
//        //1、构造Redis中的key （推荐数据）
//        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
//        //2、调用Redis查询数据：value（vid的字符串）
//        String value = redisTemplate.opsForValue().get(key);
//        //3、判断：如果redis中的数据不存在，调用API根据时间排序查询
//        List<Video> list = new ArrayList<>();
//        //如果没有推荐数据，查询数据库
//        if(StringUtils.isEmpty(value)) {
//            list = videoApi.findAll(page,pagesize);
//        }else {
//            //31,100002,33,100007,100005,32,100004,100001,100008,100010,100003,100011,100006,30
//            String[] values = value.split(",");
//            //判断，是否存在当前页的数据 1,2
//            if ((page-1) * pagesize < values.length) {
//                List<Long> vids = Arrays.stream(values)
//                        .skip((page - 1) * pagesize)
//                        .limit(pagesize)
//                        .map(e -> Long.valueOf(e))  //对数组中每个元素进行处理
//                        .collect(Collectors.toList()); //获取list集合
//                list = videoApi.findByVids(vids);
//            }else {
//                //公式  20 / 10 = 2   查询第4页   ： 2
//                int redisPage = PageUtil.totalPage(values.length, pagesize);
//                //page - 20 / 10
//                list = videoApi.findAll(page-redisPage,pagesize); //如果redis推荐数据不足，查询mongodb
//            }
//        }
//
//        //------------List<Video>----------------
//        //6、将List<Video> 转化为 List<VideoVo>
//        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
//        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
//        //循环构造
//        List<VideoVo> vos = new ArrayList<>();
//        for (Video video : list) {
//            UserInfo info = map.get(video.getUserId());
//            if(info != null) {
//                VideoVo vo = VideoVo.init(info, video);
//                vos.add(vo);
//            }
//        }
//
//        return new PageResult(page,pagesize,0l,vos);
//    }
}
